package ch.hearc.infrarouge.models;

import java.util.LinkedList;
import java.util.List;

import ch.hearc.infrarouge.database.DBCache;

/**
 * Model that represents a message of a forum thread.
 * 
 * @author Nils Amiet
 * 
 */
public class ThreadMessage {
	private String message;
	private User author;
	private ForumThread forumThread;
	private long messageId;
	private long timestamp;

	public ThreadMessage() {

	}

	public ThreadMessage(String message, User author, ForumThread forumThread,
			long messageId, long timestamp) {
		this.message = message;
		this.author = author;
		this.forumThread = forumThread;
		this.messageId = messageId;
		this.timestamp = timestamp;
	}

	@Override
	public String toString() {
		return this.author + " said: " + this.message + "\nin "
				+ this.forumThread;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public User getAuthor() {
		return author;
	}

	public void setAuthor(User author) {
		this.author = author;
	}

	public ForumThread getForumThread() {
		return forumThread;
	}

	public void setForumThread(ForumThread forumThread) {
		this.forumThread = forumThread;
	}

	public long getMessageId() {
		return messageId;
	}

	public void setMessageId(long messageId) {
		this.messageId = messageId;
	}

	public long getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(long timestamp) {
		this.timestamp = timestamp;
	}

	public List<Reply> extractReplies(boolean isFirstPost) {
		List<Reply> replies = new LinkedList<>();

		// this is the first post, so it can't be a reply
		if (isFirstPost) {
			return replies;
		}

		String message = this.message;

		while (message.contains("@")) {
			String[] split = message.split("@");
			String replyTo = split[1].split(" ")[0];

			if (replyTo.isEmpty()) {
				// some users don't use the quote feature and write "@ name" by
				// hand
				replyTo = split[1].split(" ")[1].split("<")[0];
			} else {
				replyTo = replyTo.split("<")[0];
			}

			User replyToUser = DBCache.getInstance().findUser(replyTo, -1);

			Reply reply = new Reply(this.author, replyToUser, this);
			replies.add(reply);

			message = message.substring(split[0].length() + 1);
		}

		if (replies.isEmpty()) {
			// this is not a directed reply so it is a reply to the original
			// poster (first post author)
			Reply reply = new Reply(this.author, this.forumThread.getAuthor(),
					this);
			replies.add(reply);
		}

		return replies;
	}
}
